<template>
  <div class="lottery-container">
    <van-nav-bar
      title="幸运抽奖"
      left-arrow
      @click-left="onClickLeft"
      fixed
      placeholder
    />
    
    <div class="lottery-content">
      <div class="lottery-grid">
        <div 
          v-for="(prize, index) in displayPrizes" 
          :key="prize.id"
          class="prize-item"
          :class="{ 
            'active': currentIndex === index,
            'placeholder': prize.id < 0 
          }"
        >
          <div class="prize-image">
            <van-image
              :src="getImageUrl(prize.image)"
              width="100%"
              height="100%"
              fit="cover"
              radius="8"
            />
          </div>
          <div class="prize-info">
            <span class="prize-name">{{ prize.name }}</span>
            <span v-if="prize.value > 0" class="prize-value">¥{{ prize.value }}</span>
          </div>
        </div>
      </div>
      
      <div class="lottery-button">
        <van-button 
          round 
          block 
          type="primary" 
          size="large"
          :loading="loading"
          :disabled="!canDraw"
          @click="handleDraw"
        >
          {{ loading ? '抽奖中...' : '开始抽奖' }}
        </van-button>
      </div>
    </div>
    
    <van-popup
      v-model:show="showResult"
      round
      closeable
      :style="{ width: '85%', padding: '20px' }"
    >
      <div class="result-content">
        <div class="result-title">恭喜您获得</div>
        <div class="result-prize">
          <van-image
            :src="getImageUrl(currentPrize?.image)"
            width="120"
            height="120"
            fit="cover"
            radius="12"
          />
          <div class="prize-details">
            <div class="prize-name">{{ currentPrize?.name }}</div>
            <div class="prize-value">价值: ¥{{ currentPrize?.value }}</div>
          </div>
        </div>
        <div class="result-tips">奖品将在活动结束后统一发放</div>
      </div>
    </van-popup>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { showToast } from 'vant'
import { lotteryApi, prizeApi } from '../api'
import type {PageResult, Prize} from '../api/types'
import config from '../config'

const router = useRouter()
const loading = ref(false)
const showResult = ref(false)
const currentIndex = ref(-1)
const prizes = ref<PageResult<Prize>>({ records: [], total: 0, size: 0, current: 0 })
const currentPrize = ref<Prize | null>(null)

// 获取图片完整URL
const getImageUrl = (image: string) => {
  if (!image) return ''
  if (image.startsWith('http')) return image
  // 如果是相对路径，使用静态文件服务器地址
  return `${config.staticUrl}${image}`
}

// 计算显示的奖品列表（固定6个位置）
const displayPrizes = computed(() => {
  const actualPrizes = prizes.value.records
  const displayList = [...actualPrizes]
  
  // 如果实际奖品数量不足6个，添加占位奖品
  while (displayList.length < 6) {
    displayList.push({
      id: -displayList.length, // 使用负数ID避免与实际奖品ID冲突
      name: '敬请期待',
      value: 0,
      image: config.staticUrl+'/srv/upload/static/qidai.png', // 需要添加一个占位图片
      count: 0,
      createTime: '',
      updateTime: ''
    })
  }
  
  return displayList
})

// 是否可以抽奖
const canDraw = computed(() => {
  const phone = localStorage.getItem('userPhone')
  const name = localStorage.getItem('userName')
  return phone && name
})

// 获取奖品列表
const loadPrizes = async () => {
  try {
    const res = await prizeApi.getList()
    const data = res.data as unknown
    if (data && 
        typeof data === 'object' && 
        'records' in data && 
        'total' in data && 
        'size' in data && 
        'current' in data) {
      prizes.value = data as PageResult<Prize>
    } else {
      showToast('奖品数据格式错误')
    }
  } catch (error) {
    showToast('获取奖品列表失败')
  }
}

// 开始抽奖动画
const startAnimation = () => {
  let times = 0
  const totalTimes = 10 // 增加动画次数
  const timer = setInterval(() => {
    currentIndex.value = (currentIndex.value + 1) % displayPrizes.value.length
    times++
    if (times >= totalTimes) {
      clearInterval(timer)
      showResult.value = true
    }
  }, 100)
}

// 处理抽奖
const handleDraw = async () => {
  const phone = localStorage.getItem('userPhone')
  const name = localStorage.getItem('userName')
  const company = localStorage.getItem('userCompany')
  
  if (!phone || !name) {
    showToast('请先完成问卷调查')
    router.push('/survey')
    return
  }
  
  try {
    loading.value = true
    const res = await lotteryApi.draw(phone)
    // 只在实际奖品中查找
    console.log(res.data)
    console.log(prizes.value.records)
    currentPrize.value = prizes.value.records.find(p => p.id === res.data.id) || null
    console.log(currentPrize.value)
    startAnimation()
  } catch (error: any) {
    showToast(error.message || '抽奖失败')
  } finally {
    loading.value = false
  }
}

const onClickLeft = () => {
  router.back()
}

onMounted(() => {
  loadPrizes()
})
</script>

<style scoped>
.lottery-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  overflow-x: hidden;
}

.lottery-content {
  padding: 16px;
  padding-top: 0;
  box-sizing: border-box;
  width: 100%;
  max-width: 100vw;
}

.lottery-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 8px;
  margin: 16px 0;
  background: #fff;
  padding: 12px;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  width: 100%;
  box-sizing: border-box;
}

.prize-item {
  aspect-ratio: 1;
  background-color: #f8f9fa;
  border-radius: 12px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding: 4px;
  transition: all 0.3s;
  border: 2px solid transparent;
  overflow: hidden;
  min-height: 0;
}

.prize-item.active {
  transform: scale(1.05);
  border-color: #1989fa;
  background-color: #e8f3ff;
  box-shadow: 0 4px 16px rgba(25, 137, 250, 0.15);
}

.prize-item.placeholder {
  background-color: #f5f5f5;
  border: 2px dashed #dcdee0;
}

.prize-item.placeholder .prize-name {
  color: #969799;
}

.prize-item.placeholder .prize-image {
  opacity: 0.6;
}

.prize-image {
  width: 100%;
  height: 65%;
  margin-bottom: 2px;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  align-items: center;
  justify-content: center;
}

.prize-info {
  text-align: center;
  width: 100%;
  padding: 0 2px;
  height: 35%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  overflow: hidden;
}

.prize-name {
  display: block;
  font-size: 11px;
  line-height: 1.2;
  color: #323233;
  margin-bottom: 1px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding: 0 2px;
}

.prize-value {
  display: block;
  font-size: 10px;
  line-height: 1.2;
  color: #ee0a24;
  font-weight: bold;
  padding: 0 2px;
}

.lottery-button {
  margin-top: 24px;
  padding: 0 16px;
}

.result-content {
  text-align: center;
  padding: 20px 0;
}

.result-title {
  font-size: 20px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 24px;
}

.result-prize {
  margin-bottom: 24px;
}

.prize-details {
  margin-top: 16px;
}

.prize-details .prize-name {
  font-size: 18px;
  font-weight: bold;
  color: #323233;
  margin-bottom: 8px;
}

.prize-details .prize-value {
  font-size: 16px;
  color: #ee0a24;
}

.result-tips {
  font-size: 14px;
  color: #969799;
  margin-top: 16px;
}
</style> 